﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XtremBiking.Logica
{
    public static class Usuarios
    {

        #region LogIn
        /// <summary>
        /// Method responsible for log in a backoffice user into the system.
        /// </summary>
        /// <param name="loginName">User login name</param>
        /// <param name="password">User password</param>
        /// <param name="ipAddress">IP address from which the request is made</param>
        /// <returns>LoggedUserPresentation object</returns>
        public static Tuple<String, DTO.Usuario> LogIn(string loginName, string password)
        {
            //Phoenix.Domain.DTO.BackOffice.User user;
            ////finds the user with the login name and password received
            DTO.Usuario user = null; 
            user = XtremBiking.Logica.Repositorio.UsuarioManagement.LogIn(loginName, Extensions.Encrypt(password));
            String result = "LoginIncorrecto";
            Tuple<String, DTO.Usuario> loginResult = null;
            if (user != null)
            {
                if (user.Estado == Enumerados.Usuarios.Estado.Activo)
                {
                    if (!user.primerLogin)
                    {
            //            userPresentation = new PresentationModels.Users.LoggedUserPresentation();
            //            userPresentation.UserId = user.IdUser;
            //            userPresentation.LoginName = user.LoginName;
            //            userPresentation.DisplayName = user.DisplayName;
            //            userPresentation.Email = user.Email;
            //            userPresentation.Password = user.Password;
            //            userPresentation.Status = user.Status;
            //            userPresentation.Company = new Phoenix.Facade.BackOffice.PresentationModels.Companies.ViewCompaniesPresentation() { CompanyId = user.IdCompany.ToString() };
            //            userPresentation.ProfileId = user.profileId;
            //            userPresentation.DateLastLogin = user.LastLogin;
                        result = "LoginSatisfactorio";
            //            //Process login success
            //            Phoenix.Domain.Users.LogInSuccess(user.IdUser, ipAddress);
                    }
                    else
                    {
            //            userPresentation = new PresentationModels.Users.LoggedUserPresentation();
            //            userPresentation.UserId = user.IdUser;
            //            userPresentation.ProfileId = user.profileId;
            //            userPresentation.Company = new Phoenix.Facade.BackOffice.PresentationModels.Companies.ViewCompaniesPresentation() { CompanyId = user.IdCompany.ToString() };
                        result = "PrimerLogin";
            //            //Process login success
            //            Phoenix.Domain.Users.LogInSuccess(user.IdUser, ipAddress);
                    }
                }
                else if (user.Estado == Enumerados.Usuarios.Estado.Suspendido)
                {
                    result = "Suspendido";
            //        //Process Login failed
            //        Phoenix.Domain.Users.LogInFailed(loginName, ipAddress);
                }
            }
            else
            {
            //    //Process Login failed
            //    Phoenix.Domain.Users.LogInFailed(loginName, ipAddress);
            }
            //loginResult = new Tuple<string, PresentationModels.Users.LoggedUserPresentation>(result, userPresentation);
            //return loginResult;
            loginResult = new Tuple<string, DTO.Usuario>(result, user);
           // loginResult = new Tuple<string, DTO.Usuario>("LoginSatisfactorio", user);
            return loginResult;

        }
        #endregion


        public static bool EmailAvailable(string email, string currentEmail)
        {
            bool ret = false;
            try
            {

                ret = Repositorio.UsuarioManagement.EmailAvailable(email, currentEmail);
               
            }
            catch (Exception ex)
            {

            }
            return ret;
        }


        public static bool RegistrarUsuario(DTO.Usuario modelo)
        {
            bool retorno = false;
            try
            {
                //seteo de valores por defecto
                modelo.primerLogin = true;
                modelo.Clave = Utilities.GeneratePassword();
                modelo.FechaRegistro = DateTime.Now;
                modelo.FechaUltimoLogin = DateTime.MinValue;
                modelo.Estado = Enumerados.Usuarios.Estado.Activo;

                retorno = Repositorio.UsuarioManagement.CrearUsuario(modelo);
            }
            catch (Exception ex) 
            {
                retorno = false;
                Emails.EmailErrorSistema(ex);
                throw new Exception(Recursos.Logica.Usuarios.errorRegistroUsuario);
            }
            return retorno;
        }


        #region ChangeUserPassword
        /// <summary>
        /// Method that allow the change password of a backoffice user
        /// </summary>
        /// <param name="userId">User identification</param>
        /// <param name="model">Receive an object of type UserChangePasswordPresentation</param>
        /// <param name="ipAddress">IP address from which the request is made</param>
        public static void ChangeUserPassword(DTO.UserChangePassword model)
        {
            //Phoenix.Domain.Users.EditUserPassword(userId, model.CurrentPassword, model.NewPassword, ipAddress);

            try
			{
                if (model.CurrentPassword != model.NewPassword)
                {
                    DTO.Usuario userDTO = Repositorio.UsuarioManagement.SelectById(model.IdUsuario);
                    if (userDTO != null)
                    {
                        //check if the current password entered, matches the password registered in the system
						if (userDTO.Clave == Extensions.Encrypt(model.CurrentPassword))
                        {
                            userDTO.Clave = Extensions.Encrypt(model.NewPassword);
                            //userDTO.LoginsAttempts = 0;
                            userDTO.primerLogin = false;

                            //DTO.BackOffice.BackOfficeActionHistory action = new DTO.BackOffice.BackOfficeActionHistory()
                            //{
                            //    Date = DateTime.UtcNow,
                            //    IdAction = (int)Enumerations.BackOfficeActions.ChangePassword,
                            //    IdBackOfficeUser = userId,
                            //    Description = Phoenix.Resources.Domain.Enumerations.BackOfficeActions.ChangePassword,
                            //    IpAddress = ipAddress
                            //};
                            
                            Repositorio.UsuarioManagement.UpdateUserPassword(userDTO);
                        }
                        else 
                        {
                          // throw new Exceptions.PhoenixPropagateException(Phoenix.Resources.Domain.Users.CurrentPasswordError);      
                        }
                    }
                }
                else
                {
                   // throw new Exceptions.PhoenixPropagateException(Phoenix.Resources.Domain.Users.ChangePasswordValidationError);
                }
			}
			catch (Exception ex)
			{
                
				//ExceptionHandlingManager.Handle(ex, MethodInfo.GetCurrentMethod(), Assembly.GetExecutingAssembly().FullName);
			}


            //Repositorio.UsuarioManagement.EditUserPassword()
        }
        #endregion

        #region GetByIdForLoggedUser
        /// <summary>
        /// Method that returns an logged user information by their identification
        /// </summary>
        /// <param name="id">User identification</param>
        /// <returns>Returns an object of type LoggedUserPresentation</returns>
        //public static PresentationModels.Users.LoggedUserPresentation GetByIdForLoggedUser(int id)
        //{
        //    Phoenix.Domain.DTO.BackOffice.User user = Phoenix.Domain.Users.GetById(id);
        //    PresentationModels.Users.LoggedUserPresentation userPresentation = new PresentationModels.Users.LoggedUserPresentation();
        //    userPresentation.UserId = user.IdUser;
        //    userPresentation.DisplayName = user.DisplayName;
        //    userPresentation.LoginName = user.LoginName;
        //    userPresentation.ProfileId = user.profileId;
        //    userPresentation.Company = new PresentationModels.Companies.ViewCompaniesPresentation()
        //    {
        //        CompanyId = user.IdCompany.ToString(),
        //        Name = user.CompanyName
        //    };
        //    userPresentation.Email = user.Email;
        //    userPresentation.Status = user.Status;
        //    return userPresentation;
        //}
        #endregion

        public static List<DTO.Usuario> ListAllUsers()
        {
            List<DTO.Usuario> usuarios = null;
            usuarios = Repositorio.UsuarioManagement.SelectAllUsers();
            //throw new NotImplementedException();
            return usuarios;
        }

        public static DTO.PersonalInfo GetPersonalInfo(long id)
        {
            DTO.PersonalInfo info = null;
            try
            {
                info= Repositorio.UsuarioManagement.GetPersonalInfo(id);
                //throw new NotImplementedException();
            }
            catch (Exception ex)
            {

                //ExceptionHandlingManager.Handle(ex, MethodInfo.GetCurrentMethod(), Assembly.GetExecutingAssembly().FullName);
            }
            return info;
        }

        public static void SavePersonalInfo(DTO.PersonalInfo modeloDTO)
        {
            try
            {
                Repositorio.UsuarioManagement.SavePersonalInfo(modeloDTO);
                
            }
			catch (Exception ex)
			{
                
				//ExceptionHandlingManager.Handle(ex, MethodInfo.GetCurrentMethod(), Assembly.GetExecutingAssembly().FullName);
			}
        }

        public static void SaveGoal(DTO.UserGoal modeloDTO)
        {
            try
            {
                Repositorio.UsuarioManagement.SaveUserGoal(modeloDTO);

            }
            catch (Exception ex)
            {

                //ExceptionHandlingManager.Handle(ex, MethodInfo.GetCurrentMethod(), Assembly.GetExecutingAssembly().FullName);
            }
        }

        public static List<DTO.UserGoal> GetUserGoals(long idUser)
        {
            List<DTO.UserGoal> goals = null;
            try
            {
                goals = Repositorio.UsuarioManagement.GetUserGoals(idUser);
            }
            catch (Exception ex)
            {
                //ExceptionHandlingManager.Handle(ex, MethodInfo.GetCurrentMethod(), Assembly.GetExecutingAssembly().FullName);
            }
            return goals;
        }
    }
}
